package com.gientech.madp.sm2.sm;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SM4Utils
{
	private String secretKey = "";
	private String iv = "";
	private boolean hexString = false;
	
	public SM4Utils()
	{
	}
	
	public String encryptData_ECB(String plainText)
	{
		try 
		{
			SM4_Context ctx = new SM4_Context();
			ctx.isPadding = true;
			ctx.mode = SM4.SM4_ENCRYPT;
			
			byte[] keyBytes;
			if (hexString)
			{
				keyBytes = Util.hexStringToBytes(secretKey);
			}
			else
			{
				keyBytes = secretKey.getBytes();
			}
			
			SM4 sm4 = new SM4();
			sm4.sm4_setkey_enc(ctx, keyBytes);
			byte[] encrypted = sm4.sm4_crypt_ecb(ctx, plainText.getBytes("GBK"));
			String cipherText = new BASE64Encoder().encode(encrypted);
			if (cipherText != null && cipherText.trim().length() > 0)
			{
				Pattern p = Pattern.compile("\\s*|\t|\r|\n");
				Matcher m = p.matcher(cipherText);
				cipherText = m.replaceAll("");
			}
			return cipherText;
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			return null;
		}
	}
	
	public String decryptData_ECB(String cipherText)
	{
		try 
		{
			SM4_Context ctx = new SM4_Context();
			ctx.isPadding = true;
			ctx.mode = SM4.SM4_DECRYPT;
			
			byte[] keyBytes;
			if (hexString)
			{
				keyBytes = Util.hexStringToBytes(secretKey);
			}
			else
			{
				keyBytes = secretKey.getBytes();
			}
			
			SM4 sm4 = new SM4();
			sm4.sm4_setkey_dec(ctx, keyBytes);
//			byte[] decrypted = sm4.sm4_crypt_ecb(ctx, new BASE64Decoder().decodeBuffer(cipherText));
			byte[] decrypted = sm4.sm4_crypt_ecb(ctx, Base64.getDecoder().decode(cipherText));
//			return new String(decrypted, "GBK");
			return new String(decrypted, StandardCharsets.UTF_8);
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			return null;
		}
	}
	
	public String encryptData_CBC(String plainText)
	{
		try 
		{
			SM4_Context ctx = new SM4_Context();
			ctx.isPadding = true;
			ctx.mode = SM4.SM4_ENCRYPT;
			
			byte[] keyBytes;
			byte[] ivBytes;
			if (hexString)
			{
				keyBytes = Util.hexStringToBytes(secretKey);
				ivBytes = Util.hexStringToBytes(iv);
			}
			else
			{
				keyBytes = secretKey.getBytes();
				ivBytes = iv.getBytes();
			}
			
			SM4 sm4 = new SM4();
			sm4.sm4_setkey_enc(ctx, keyBytes);
			byte[] encrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, plainText.getBytes("GBK"));
			String cipherText = new BASE64Encoder().encode(encrypted);
			if (cipherText != null && cipherText.trim().length() > 0)
			{
				Pattern p = Pattern.compile("\\s*|\t|\r|\n");
				Matcher m = p.matcher(cipherText);
				cipherText = m.replaceAll("");
			}
			return cipherText;
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			return null;
		}
	}
	
	public String decryptData_CBC(String cipherText)
	{
		try 
		{
			SM4_Context ctx = new SM4_Context();
			ctx.isPadding = true;
			ctx.mode = SM4.SM4_DECRYPT;
			
			byte[] keyBytes;
			byte[] ivBytes;
			if (hexString)
			{
				keyBytes = Util.hexStringToBytes(secretKey);
				ivBytes = Util.hexStringToBytes(iv);
			}
			else
			{
				keyBytes = secretKey.getBytes();
				ivBytes = iv.getBytes();
			}
			
			SM4 sm4 = new SM4();
			sm4.sm4_setkey_dec(ctx, keyBytes);
			byte[] decrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, new BASE64Decoder().decodeBuffer(cipherText));
			return new String(decrypted, "GBK");
		} 
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
	
	public static void main(String[] args) throws IOException 
	{
		String plainText = "{\n" +
				"        \"reqHead\": {\n" +
				"            \"vrsn\": \"1.0.0\",\n" +
				"            \"txnDt\": \"2021/09/18\",\n" +
				"            \"pageSize\": \"\",\n" +
				"            \"svcCd\": \"AsCapGetRandom\",\n" +
				"            \"chnlGrpCd\": \"100\",\n" +
				"            \"cnsmrChnlTpCd\": \"\",\n" +
				"            \"mac\": \"\",\n" +
				"            \"orgId\": \"087190007\",\n" +
				"            \"eventNo\": \"\",\n" +
				"            \"txnTlrId\": \"MPB00001\",\n" +
				"            \"svcScn\": \"01\",\n" +
				"            \"cnsmrSysId\": \"305105\",\n" +
				"            \"cnsmrSeqNo\": \"\",\n" +
				"            \"pageIndex\": \"\",\n" +
				"            \"txnChnlTp\": \"105\",\n" +
				"            \"lglPrsnCd\": \"9999\",\n" +
				"            \"txnTmlId\": \"\",\n" +
				"            \"txnTm\": \"\",\n" +
				"            \"origIttAplNo\": \"100200\"\n" +
				"        },\n" +
				"        \"pswdTp\": \"01\",\n" +
				"        \"sign\": {\n" +
				"            \"signature\": \"6f57cca7ca56926ca5ded71024ca2940df48ec48092d1ec7a3115a74a9a9f14bc27fe538ce21b42a9f90ec0804c28be5e27329a189f33704b693fbde9dcbccee\",\n" +
				"            \"signType\": \"SM2\"\n" +
				"        }\n" +
				"    }";
		
		SM4Utils sm4Utils = new SM4Utils();
//		sm4.secretKey = "JeF8U9wHFOMfs2Y8";
		sm4Utils.secretKey = "11HDESaAhiHHugDz";
		sm4Utils.hexString = false;
		
		System.out.println("ECB模式");
		String cipherText = sm4Utils.encryptData_ECB(plainText);
		System.out.println("密文: " + cipherText);
		System.out.println("");
//		cipherText = "CvHb9ZA3AkR/tJjZHh+5+e98LJCJJDcK28w7dZcMO1XLVBueenGzQ+83d0F7VOT4rlWYkfWQwyn8No4BMk/nz6xjmOpWFRz1P6ae49639Te0YU6dWnpdl8rsSTJJOmT5fLCshmlHLvQYjQDfuDiBDBL1jJppsWrkR/BxYvzfaZeF1dNKjEwE4lmAGeN62geFyNr+nq0czamBMqS3Pvy+i84Z7VnPDF2Wc3lJnbEBkf/LCd8/fLgB+vB5QiAXlUvLhVAtA9kCtunK3elv8ntSr/rm9G3GOnN2LJ+DlrekRwMLZkrJ6X84otkp2nWinQ7GuGHuEiOGd5mIuzUnDLD0+wnMo4E3Sd99EgiMhlUOKDU73kFQgCYRqQq+PP32x+u+S4ERazGT9LmyzK8ikkgl+doNC6vOxhrY0t1wwFo9wkrfaqpQlFj7J58Hl/wT1fRGRVaY+yi2AWbRmw3uyOGnHUQFcUBJAdO37MeXPf2v94bjUa4y+2BpM5P5vGhKt7LbF8NyW5tr5TwR7imoLGp2zZ1hrWDZCUs/Bj5ygQn5+ThNxeBR2VCxKWSNn16frMnSDHKDcRepYkIH7efVbe73MLpFVTDgoL9y2a3njXQ6/flaotN3Q7KQap38Kzf/jTWvgaQox6xvWYxNGZbnarwA1gwsxjWRQE+eOF7VcQ/4SkatgZ+I54kHJ+T0vNw3QPigC2UpB6EKLdOhoUlEQZeQPNHgcjmga3c9BjqNf6ZNur5ezFzDbWlrBS+VFzWVdlGyJJSABw6qKNpT+LSCtEygFY3Ebqf2fnrfovlQ90ZsxV58rKZD4tVucdDUbu1l5YoWhI/dhyCY0vVNZqizSqjdEaVhyvMeh/F4H0BtIYlcEwAwg/tel8XncbZ26SkXG6WtrrDHJYEdcVFrMLvwYkY2rmVlITfqobXIitYvf8TYuwZ6g7FxPaz9Dsd+iXJBhDm2+gXdjRyg1Q7tSowJp8XisQ==";
		plainText = sm4Utils.decryptData_ECB(cipherText);
		System.out.println("明文: " + plainText);
		System.out.println("");
		
		System.out.println("CBC模式");
		sm4Utils.iv = "UISwD9fW6cFh9SNS";
		cipherText = sm4Utils.encryptData_CBC(plainText);
		System.out.println("密文: " + cipherText);
		System.out.println("");
		
		plainText = sm4Utils.decryptData_CBC(cipherText);
		System.out.println("明文: " + plainText);
	}
}
